<template>
	<view class="container" v-if="currentSession.length > 0">
		<!-- 浮动提示按钮 -->
		<view v-if="currentSession.length > 0" class="notification-btn" :style="{ opacity: showButton ? 1 : 0 }" @click="handleNotificationClick" @longpress="toContacts">
			<view class="avatar-container" :class="{ blink: isBlinking }">
				<image class="avatar" :src="nicPic" mode="aspectFill" />
				<view v-if="currentSession[0].unreadCount > 0" class="badge">
					<text style="color: white; font-size: 25rpx">{{ currentSession[0].unreadCount }}</text>
				</view>
			</view>
			<view>
				<text style="font-size: 24rpx">{{ currentSession.name ? currentSession.name : currentSession.id }}</text>
			</view>
		</view>
	</view>
</template>

<script>
import { processReceivedMessage, initializeData } from '../utils/chatList.js';

export default {
	name: 'contactsTabs',

	data() {
		return {
			chatList: [],
			currentSession: [],
			showButton: true,
			isBlinking: true,
			nicPic: ''
		};
	},
	computed: {
		storeData() {
			return this.$store.state.msg;
		},
		currentSession
	},
watch: {
  chatList: {
    async handler(newval) {
      // 过滤出有未读消息的会话
      const unreadList = newval.filter(item => item.unreadCount > 0);
      
      if (unreadList.length > 0) {
        // 按时间戳降序排序（最新的在前）
        this.currentSession = unreadList.sort((a, b) => b.timestamp - a.timestamp);
        // 计算总未读数量
        const totalUnread = this.currentSession.reduce((sum, item) => sum + item.unreadCount, 0);
        this.$emit('msgCount', totalUnread);
        
        // 获取第一个会话的目标信息
        try {
          await this.getTargetInfo(
            this.currentSession[0].userId, 
            this.currentSession[0].type
          );
        } catch (e) {
          console.error("获取目标信息失败：", e); // 使用error更规范
        }
      } else {
        // 没有未读消息时，重置状态并通知父组件
        this.currentSession = [];
        this.$emit('msgCount', 0);
      }
    }
  }
},
	async created() {
		this.chatList = await initializeData();

	},
	async mounted() {
		uni.$on('private_msg', (res) => {
			console.log('私聊天信',res);
			this.getChatList(res);
		});
		uni.$on('group_msg', (res) => {
			this.getChatList(res);
		});
		uni.$on('newMsgNotice', (res) => {
			this.getChatList(res);
		});
		uni.$on('readmessages', (res) => {
			this.clearUnRead(res);
		});
	},
	methods: {
		async getChatList(newMsg) {
			try{
				for (const msg of [newMsg]) {
				this.chatList = await processReceivedMessage(msg, this.storeData.user);
			}	
			}catch(e){
				console.log('错误',e);
			}
		
		},
		//消除未读标记
		async clearUnRead(msglist) {
			for (const msg of msglist) {
				if (msg.toTarget.targetType === '3') {
					const userid = msg.sendUserId === getApp().globalData.user.userId ? msg.toTarget.targetId : msg.sendUserId;

					const index = this.chatList.findIndex((item) => item.userId === userid);

					this.chatList[index].unreadCount = 0;
					uni.setStorageSync('chatList', this.chatList);
				}
				if (msg.toTarget.targetType === '2') {
					const index = this.chatList.findIndex((item) => item.userId === msg.toTarget.targetId);

					this.chatList[index].unreadCount = 0;
					uni.setStorageSync('chatList', this.chatList);
				}
			}
		},

		async getTargetInfo(userId, type) {
			if (type === 'person') {
				try {
					const db = uniCloud.databaseForJQL();
					const res = await db
						.collection('linli-user')
						.where({
							userId: userId
						})
						.field('nicPic')
						.get();
					this.nicPic = res.data[0].nicPic || '';
				} catch (error) {
					console.error('获取头像图片 URL 失败:', error);
					this.nicPic = ''; // 可以设置一个默认图片 URL
				}
			}
			if (type === 'group') {
				try {
					const db = uniCloud.databaseForJQL();
					const res = await db
						.collection('Group')
						.where({
							groupId: userId
						})
						.field('groupPicPath')
						.get();
					this.nicPic = res.data[0].groupPicPath || '';
				} catch (error) {
					console.error('获取头像图片 URL 失败:', error);
					this.nicPic = ''; // 可以设置一个默认图片 URL
				}
			}
		},
		handleNotificationClick() {
			//1,删除未读会话列表的相应的元素
			//2，转到此会话上
			const user = this.currentSession.shift();
			uni.navigateTo({
				url: `/pages/PrivateChat/PrivateChat?id=${user.userId}`
			});
		},
		toContacts() {}
	}
};
</script>

<style lang="scss" scoped>
.container {

	display: flex;
	width: 120rpx;
	height: 120rpx;
	border-radius: 60rpx;
	background-color: #ff4444;
	flex-direction: column;
	justify-content: center;
	align-items: center;
}

.notification-btn {
	transition: opacity 0.3s;
	width: 100rpx;
	height: 100rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	border-radius: 50rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
}

.avatar-container {
	position: relative;
	width: 100rpx;
	height: 100rpx;
	border-radius: 50rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
}

.blink {
	animation: blink 1s infinite;
}

.avatar {
	width: 100rpx;
	height: 100rpx;
	border-radius: 50rpx;
	background-color: #eee;
}

.badge {
	position: absolute;
	top: -10rpx;
	right: -10rpx;
	min-width: 36rpx;
	height: 36rpx;
	padding: 0 8rpx;
	background: #ff4444;
	color: white;
	font-size: 24rpx;
	border-radius: 40rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border: 1rpx solid white;
}

.view {
	margin-top: 10rpx;
	font-size: 25rpx;
	text-align: center;
}

.notification-btn-no-unread {
	transition: opacity 0.3s;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	border-radius: 10rpx;
}

.no-unread-image {
	width: 45rpx;
	height: 45rpx;
}

.book {
	margin-top: 2rpx;
	font-size: 25rpx;
}
</style>
